package com.woniuxy.controller;

import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;
import com.woniuxy.utils.JWTUtils;
import com.woniuxy.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(tags = "登录接口")
public class LoginController {
    @Autowired(required = false)
    UserService userService;

    @GetMapping("/login")
    @ApiOperation(value = "用户登录")
    public ResponseEntity login(@ApiParam(name = "用户名", value="username")String username, @ApiParam(name = "密码", value="password")String password){
        //根据username获取user
        User user1 = userService.findByUsername(username);
        //加盐
        String encryptPassword = MD5Util.encryptPassword(password, user1.getSalt());
        User user = userService.login(username, encryptPassword);
        if (!StringUtils.isEmpty(user)){
            //就说明查出了用户数据
            String token =  JWTUtils.sign(username, password);
            user.setToken(token);
            return new ResponseEntity<>(200,"登录成功",user);
        }else {
            return ResponseEntity.Fail;
        }
    }

    @RequestMapping("/401")
    @CrossOrigin
    @ApiOperation(value = "登录失败")
    public ResponseEntity response401(){
        return new ResponseEntity(401,"认证异常！",null);
    }
}
